﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using LM.YF.K3Cloud.Plugin.Models;
using LM.YF.K3Cloud.Plugin.Models.Grasses;
using LM.YF.K3Cloud.Plugin.Models.VOs;
using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace LM.YF.K3Cloud.Plugin
{
    /// <summary>
    /// 鹿奔 240515
    /// </summary>
    [HotUpdate, Description("操作前计算结算单价（挂载到销售退货单的保存操作）")]
    public class CalcSettlementPriceOperationServicePlugin2 : AbstractOperationServicePlugIn
    {
        #region MyRegion

        /// <summary>
        /// 销售组织
        /// </summary>
        private readonly ElementKeySchema FSaleOrgId = new ElementKeySchema
        {
            FormKey = "FSaleOrgId",
            DbKey = "FSALEORGID",
            OrmKey = "SaleOrgId"
        };

        /// <summary>
        /// 库存组织
        /// </summary>
        private readonly ElementKeySchema FStockOrgId = new ElementKeySchema
        {
            FormKey = "FStockOrgId",
            DbKey = "FSTOCKORGID",
            OrmKey = "StockOrgId"
        };

        /// <summary>
        /// 含税单价
        /// </summary>
        private readonly ElementKeySchema FTaxPrice = new ElementKeySchema
        {
            FormKey = "FTaxPrice",
            DbKey = "FTAXPRICE",
            OrmKey = "TaxPrice"
        };

        /// <summary>
        /// 结算单价
        /// </summary>
        private readonly ElementKeySchema F_RDLV_settlement_price = new ElementKeySchema
        {
            FormKey = "F_RDLV_settlement_price",
            DbKey = "F_RDLV_settlement_price",
            OrmKey = "F_RDLV_settlement_price"
        };

        /// <summary>
        /// 销售主体
        /// </summary>
        private readonly ElementKeySchema F_RDLV_saleBody = new ElementKeySchema
        {
            FormKey = "F_RDLV_saleBody",
            DbKey = "F_RDLV_SALEBODY",
            OrmKey = "F_RDLV_saleBody"
        };

        /// <summary>
        /// 单据编号
        /// </summary>
        private readonly ElementKeySchema FBillNo = new ElementKeySchema
        {
            FormKey = "FBillNo",
            DbKey = "FBILLNO",
            OrmKey = "BillNo"
        };

        /// <summary>
        /// 物料编码
        /// </summary>
        private readonly ElementKeySchema FMaterialID = new ElementKeySchema
        {
            FormKey = "FMaterialID",
            DbKey = "FMATERIALID",
            OrmKey = "MaterialID"
        };

        /// <summary>
        /// 币别
        /// </summary>
        private readonly ElementKeySchema FSettleCurrId = new ElementKeySchema
        {
            FormKey = "FSettleCurrId",
            DbKey = "FSETTLECURRID",
            OrmKey = "SettleCurrId"
        };

        /// <summary>
        /// 汇率
        /// </summary>
        private readonly ElementKeySchema FExchangeRate = new ElementKeySchema
        {
            FormKey = "FExchangeRate",
            DbKey = "FEXCHANGERATE",
            OrmKey = "ExchangeRate"
        };

        /// <summary>
        /// 结算系数
        /// </summary>
        private readonly ElementKeySchema F_RDLV_coefficient = new ElementKeySchema
        {
            FormKey = "F_RDLV_coefficient",
            DbKey = "F_RDLV_COEFFICIENT",
            OrmKey = "F_RDLV_coefficient"
        };

        /// <summary>
        /// 明细单据体
        /// </summary>
        private readonly ElementKeySchema FEntity = new ElementKeySchema
        {
            FormKey = "FEntity",
            DbKey = "T_SAL_RETURNSTOCKENTRY",
            OrmKey = "SAL_RETURNSTOCKENTRY"
        };

        /// <summary>
        /// 财务信息单据体
        /// </summary>
        private readonly ElementKeySchema SubHeadEntity = new ElementKeySchema
        {
            FormKey = "SubHeadEntity",
            DbKey = "T_SAL_RETURNSTOCKFIN",
            OrmKey = "SAL_RETURNSTOCKFIN"
        };

        /// <summary>
        /// 明细单据体-海空运费
        /// </summary>
        private readonly ElementKeySchema F_QLTK_SeaAirFreight = new ElementKeySchema
        {
            FormKey = "F_QLTK_SeaAirFreight",
            DbKey = "F_QLTK_SEAAIRFREIGHT",
            OrmKey = "F_QLTK_SeaAirFreight"
        };

        /// <summary>
        /// 明细单据体-保费
        /// </summary>
        private readonly ElementKeySchema F_QLTK_PREMIUM = new ElementKeySchema
        {
            FormKey = "F_QLTK_PREMIUM",
            DbKey = "F_QLTK_PREMIUM",
            OrmKey = "F_QLTK_PREMIUM"
        };

        /// <summary>
        /// 明细单据体-佣金
        /// </summary>
        private readonly ElementKeySchema F_QLTK_Commission = new ElementKeySchema
        {
            FormKey = "F_QLTK_Commission",
            DbKey = "F_QLTK_COMMISSION",
            OrmKey = "F_QLTK_Commission"
        };

        /// <summary>
        /// 明细单据体-其他1
        /// </summary>
        private readonly ElementKeySchema F_QLTK_Other1 = new ElementKeySchema
        {
            FormKey = "F_QLTK_Other1",
            DbKey = "F_QLTK_OTHER1",
            OrmKey = "F_QLTK_Other1"
        };

        /// <summary>
        /// 计价数量
        /// </summary>
        private readonly ElementKeySchema FPriceUnitQty = new ElementKeySchema
        {
            FormKey = "FPriceUnitQty",
            DbKey = "FPRICEUNITQTY",
            OrmKey = "PriceUnitQty"
        };

        /// <summary>
        /// 税率
        /// </summary>
        private readonly ElementKeySchema FEntryTaxRate = new ElementKeySchema
        {
            FormKey = "FEntryTaxRate",
            DbKey = "FTAXRATE",
            OrmKey = "TaxRate"
        };

        /// <summary>
        /// 本位币
        /// </summary>
        private readonly ElementKeySchema FLocalCurrId = new ElementKeySchema
        {
            FormKey = "FLocalCurrId",
            DbKey = "FLOCALCURRID",
            OrmKey = "LocalCurrId"
        };

        /// <summary>
        /// 折扣额
        /// </summary>
        private readonly ElementKeySchema FDiscount = new ElementKeySchema
        {
            FormKey = "FDiscount",
            DbKey = "FDISCOUNT",
            OrmKey = "Discount"
        };

        #endregion

        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);

            e.FieldKeys.Add(FStockOrgId.FormKey);
            e.FieldKeys.Add(FTaxPrice.FormKey);
            e.FieldKeys.Add(F_RDLV_settlement_price.FormKey);
            e.FieldKeys.Add(F_RDLV_saleBody.FormKey);
            e.FieldKeys.Add(FBillNo.FormKey);
            e.FieldKeys.Add(FMaterialID.FormKey);
            e.FieldKeys.Add(FSettleCurrId.FormKey);
            e.FieldKeys.Add(FExchangeRate.FormKey);
            e.FieldKeys.Add(F_RDLV_coefficient.FormKey);
        }

        public override void BeforeExecuteOperationTransaction(BeforeExecuteOperationTransaction e)
        {
            base.BeforeExecuteOperationTransaction(e);

            var failureList = new List<string>();
            foreach (var row in e.SelectedRows)
            {
                var failure = BeforeExecuteOperationTransaction(row);
                if (failure != null)
                {
                    failureList.Add(failure);
                }
            }
            if (failureList.Count > 0)
            {
                throw new KDBusinessException(null, string.Join("\r\n", failureList));
            }
        }

        private string BeforeExecuteOperationTransaction(ExtendedDataEntity row)
        {
            var dataEntity = row.DataEntity;
            var objSaleOrg = dataEntity[FSaleOrgId.OrmKey] as DynamicObject;
            var objSaleOrgName = (objSaleOrg?["Name"] as LocaleValue)?[2052];
            var objStockOrg = dataEntity[FStockOrgId.OrmKey] as DynamicObject;
            var stockOrgName = (objStockOrg?["Name"] as LocaleValue)?[2052];

            if (!(/*new string[] { "利民控股集团股份有限公司", "河北威远生物化工有限公司" }.Contains(objSaleOrgName)
               &&*/ !stockOrgName.Equals(objSaleOrgName)))
            {
                return null;
            }

            var stockOrgId = Convert.ToInt32(objStockOrg["Id"]);
            var saleOrgId = Convert.ToInt32(objSaleOrg["Id"]);
            var salerId = Convert.ToInt32((dataEntity[F_RDLV_saleBody.OrmKey] as DynamicObject)?["Id"]);
            if (stockOrgId == 0 || saleOrgId == 0 || salerId == 0)
            {
                return null;
            }

            var exchangeRate = 1M;// 汇率
            var finEntities = dataEntity[SubHeadEntity.OrmKey] as DynamicObjectCollection;
            var finEntity = finEntities[0];
            var settleCurr = Convert.ToInt32((finEntity[FSettleCurrId.OrmKey] as DynamicObject)?["Id"]);
            var isCny = settleCurr == 1;// 是否为人民币
            if (!isCny)
            {
                exchangeRate = Convert.ToDecimal(finEntity[FExchangeRate.OrmKey]);
            }
            var entries = dataEntity[FEntity.OrmKey] as DynamicObjectCollection;

            var localCurrId = Convert.ToInt32((finEntity[FLocalCurrId.OrmKey] as DynamicObject)?["Id"]);
            var vo = new avnn1
            {
                StockOrgId = stockOrgId,
                SalerId = salerId,
                EntryDataCount = entries.Count,
                ExchangeRate = exchangeRate,
                SaleOrgId = saleOrgId,
                LocalCurrId = localCurrId
            };
            var vo2 = new vna1
            {
                GetInputs = entryIndex =>
                {
                    var entry = entries[entryIndex];
                    return new smznb111
                    {
                        MaterialId = Convert.ToInt32((entry[FMaterialID.OrmKey] as DynamicObject)?["Id"]),
                        Commission = Convert.ToDecimal(entry[F_QLTK_Commission.OrmKey]),
                        OtherFee = Convert.ToDecimal(entry[F_QLTK_Other1.OrmKey]),
                        Premium = Convert.ToDecimal(entry[F_QLTK_PREMIUM.OrmKey]),
                        PriceQty = Convert.ToDecimal(entry[FPriceUnitQty.OrmKey]),
                        SaFreight = Convert.ToDecimal(entry[F_QLTK_SeaAirFreight.OrmKey]),
                        TaxPrice = Convert.ToDecimal(entry[FTaxPrice.OrmKey]),
                        TaxRate = Convert.ToDecimal(entry[FEntryTaxRate.OrmKey]),
                        Discount = Convert.ToDecimal(entry[FDiscount.OrmKey])
                    };
                },
                OnCalculated = (settlementPrice, coefficient, entryIndex) =>
                {
                    var entry = entries[entryIndex];
                    var entryId = Convert.ToInt32(entry["Id"]);
                    entry[F_RDLV_coefficient.OrmKey] = coefficient.ToString();
                    entry[F_RDLV_settlement_price.OrmKey] = settlementPrice.ToString();
                    DBUtils.Execute(Context, $@"update T_SAL_RETURNSTOCKENTRY
                    set F_RDLV_COEFFICIENT = {coefficient}, F_RDLV_SETTLEMENT_PRICE = {settlementPrice}
                    where FENTRYID = {entryId};");
                }
            };
            var failure = CalcSettlementPriceOperationServicePlugin.CalcSettlementPrice(Context, vo, vo2);

            //if (!failure.Successful)
            if (failure.Message != null)
            {
                var billNo = dataEntity[FBillNo.OrmKey]?.ToString();
                return $"销售退货单【{billNo}】计算结算单价失败：{failure.Message}";
            }

            return null;
        }
    }
}
